package cn.hd.userService.service.role.impl;

import cn.hd.commonService.entity.SysFunction;
import cn.hd.commonService.entity.SysRole;
import cn.hd.commonService.entity.SysRoleFunc;
import cn.hd.commonService.entity.SysUserRole;
import cn.hd.commonService.exception.CustomException;
import cn.hd.commonService.vo.Query;
import cn.hd.userService.mapper.role.SysRoleMapper;
import cn.hd.userService.service.function.ISysFunctionService;
import cn.hd.userService.service.function.impl.SysFunctionServiceImpl;
import cn.hd.userService.service.role.ISysUserRoleService;
import cn.hd.userService.service.role.SysRoleFuncService;
import cn.hd.userService.service.role.SysRoleService;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * created by dsl on 2022/6/28
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    @Autowired
    private ISysFunctionService sysFunctionService;

    @Autowired
    private SysRoleFuncService sysRoleFuncService;

    /**
     * 保存或修改角色
     * @CreatedBy dsl
     */
    public void saveOrUpdateRole(SysRole sysRole){
        if (StrUtil.isEmptyIfStr(sysRole.getRecordId())){
            sysRole.setRoleNo(maxRoleNo());
        }
        checkRole(sysRole);
        saveOrUpdate(sysRole);
    }

    /**
     * 判断角色名称是否重复
     * @CreatedBy dsl
     */
    public void checkRole(SysRole sysRole){
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getRoleName,sysRole.getRoleName()).eq(SysRole::getDeleted,0);
        SysRole one = sysRoleMapper.selectOne(wrapper);
        if (one!=null){
            if (!StrUtil.isEmptyIfStr(sysRole.getRecordId())){
                if (!sysRole.getRecordId().equals(one.getRecordId())){
                    throw new CustomException("角色名称重复");
                }
            } else {
                throw new CustomException("角色名称重复");
            }
        }
    }

    public void batchDelete(String roleIds){
        //将字符串转化为集合
        List<Integer> list = Convert.toList(Integer.class, roleIds);
        for (Integer roleId : list) {
            SysRole sysRole = sysRoleMapper.selectById(roleId);
            Optional.ofNullable(sysRole).orElseThrow(()-> new CustomException("角色信息有误"));
            List<SysUserRole> sysUserRoles = sysUserRoleService.getSysUserRoleByUserId(null, roleId);
            if (sysUserRoles!=null&&sysUserRoles.size()>0){
                throw new CustomException("当前角色关联的有人员，不能删除");
            }
        }
        //批量删除
        sysRoleFuncService.deleteByRoleId(list);
        sysRoleMapper.deleteBatchIds(list);
    }

    @Override
    public IPage<SysRole> getListByPage(Query query, String roleName) {
        Page<SysRole> page = new Page<>(query.getCurrentPage(),query.getPageSize());
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        if (!StrUtil.isBlankIfStr(roleName)){
            wrapper.like(SysRole::getRoleName,roleName);
        }
        wrapper.orderByDesc(SysRole::getRoleNo);
        return sysRoleMapper.selectPage(page,wrapper);
    }
    /**
     * 获取最大排序号
     * @return
     */
    public int maxRoleNo(){
        return Convert.toInt(sysRoleMapper.maxOrderNo(),0)+1;
    }

    @Override
    public List<SysRole> getRoleList(List<Integer> roleIds) {
        List<SysRole> result = new ArrayList<>();
        if (roleIds != null && !roleIds.isEmpty()){
            result =  sysRoleMapper.selectBatchIds(roleIds);
        }
        return result;
    }

    /**
     * @CreatedBy dsl
     * 通过角色id获取已授权的资源
     */
    @Override
    public List<SysFunction> getFunctionListByRoleId(int roleId) {
        List<SysFunction> functionList = new ArrayList<>();
        //通过角色id获取关联关系
        List<SysRoleFunc> listByRoleId = sysRoleFuncService.getListByRoleId(roleId);
        List<Integer> functionId = listByRoleId.stream().map(sysRoleFunc -> sysRoleFunc.getFunctionId()).collect(Collectors.toList());
        if (functionId != null && !functionId.isEmpty()){
            functionList = sysFunctionService.getFunctionList(functionId);
        }
        return functionList;
    }
}
